package com.zhouyibike.uu.ui.activity.mybike;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.TransferForDoingResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.listener.MyListener;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.PinnedSectionListView;
import com.zhouyibike.uu.ui.view.PullToRefreshLayout;
import com.zhouyibike.uu.utils.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by Zy on 2017/10/11.
 */
public class MyBikejiaoyi1Fragment extends Fragment implements View.OnClickListener {
    private List<TransferForDoingResult.DataBean> alllist = new ArrayList<>();
    private ListView lv_allmsg;
    private SimpleAdapter smadapter;
    private PullToRefreshLayout pullToRefreshLayout;
    private int refreshtype = 0;
    private int page = 1;//页码
    private boolean ismore = true;//判断是否还有更多数据
    private TextView jiaoyizhuanrangtv, jiaoyirengoutv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Bundle b = getArguments();
        View view = View.inflate(getActivity(), R.layout.fragment_mybikejiaoyi1, null);
        //  type=getIntent().getStringExtra("type");
        initView(view);
        getMsggg();
        //  getMsg();
        // ((BaseActivity) getActivity()).toastShow(b.getString("type"));
        initlistener();
        return view;
    }

    private void initlistener() {
        jiaoyirengoutv.setOnClickListener(this);
        jiaoyizhuanrangtv.setOnClickListener(this);
    }

    private void initView(View view) {
        pullToRefreshLayout = ((PullToRefreshLayout) view.findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(new MyListener2());
//        ll_nothing = (LinearLayout) findViewById(R.id.ll_nothing_show);
        lv_allmsg = (ListView) view.findViewById(R.id.content_view);
        jiaoyirengoutv = view.findViewById(R.id.jiaoyi_rengoubt);
        jiaoyizhuanrangtv = view.findViewById(R.id.jiaoyi_zhuanrangbt);
    }

    private void getMsggg() {
        Map<String, String> params = new HashMap<>();
        try {
            params.put("token", ((MybikeActivity6) getActivity()).preferences.getString("token", ""));
        } catch (Exception e) {
            return;
        }
        params.put("pageIndex", page + "");
//        if (page == 1 && refreshtype == 0)
//            showProgressDialog();
        ((BaseActivity) getActivity()).addSubscription(((BaseActivity) getActivity()).apiStores.TransferForDoing(params),
                new ApiCallback<TransferForDoingResult>() {

                    @Override
                    public void onSuccess(TransferForDoingResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
//                            for (int i = 0; i <model.getData().size() ; i++) {
//                                Log.e("手机号: ",model.getData().get(i).getUserName());
//                            }
                            if (refreshtype == 1) {
                                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                                alllist.clear();
                            } else if (refreshtype == 2) {
                                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                            }
                            if (model.getData().size() == 0) {
                                ismore = false;
                            }
                            alllist.addAll(model.getData());
                            if (alllist.size() == 0) {
                                //  ll_nothing.setVisibility(View.VISIBLE);
                                pullToRefreshLayout.setVisibility(View.GONE);
                            } else {
                                //   ll_nothing.setVisibility(View.GONE);
                                pullToRefreshLayout.setVisibility(View.VISIBLE);
                                initDataa();
                            }

                        } else if (model.getStatus() == 508 || model.getStatus() == 506 || model.getStatus() == 307) {
                            ((BaseActivity) getActivity()).setResult(2501);
                            ((BaseActivity) getActivity()).finish();
                        } else {
                            ((BaseActivity) getActivity()).toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        ((BaseActivity) getActivity()).toastShow(msg);

                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    private void initDataa() {
        if (page == 1) {
//            myJourneyAdapter = new MyDanchejiaoyiAdapter(this, alllist);
//            lv_allmsg.setAdapter(myJourneyAdapter);
            smadapter = new SimpleAdapter(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, alllist);
            lv_allmsg.setAdapter(smadapter);
        } else {
//            myJourneyAdapter.setList(alllist);
//            smadapter=new SimpleAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1,alllist);
//            lv_allmsg.setAdapter(smadapter);
            smadapter.setlist(alllist);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.jiaoyi_rengoubt:
                Intent intent = new Intent(getActivity(), RengouActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.jiaoyi_zhuanrangbt:
                Intent intent1 = new Intent((MybikeActivity6) getActivity(), ZhuanRangActivity.class);
                intent1.putExtra("zrnum", ((MybikeActivity6) getActivity()).f1.totalnum);
                startActivityForResult(intent1, 10010);
                break;
        }
    }

    static class SimpleAdapter extends ArrayAdapter<Item> implements PinnedSectionListView.PinnedSectionListAdapter {
        Context context1;
        List<TransferForDoingResult.DataBean> listall2 = new ArrayList<>();
        private static final int[] COLORS = new int[]{
                R.color.colorAccent, R.color.bg_main_white,
                R.color.color_zhuanrang, R.color.help_view};

        public SimpleAdapter(Context context, int resource, int textViewResourceId, List<TransferForDoingResult.DataBean> listall) {
            super(context, resource, textViewResourceId);
            context1 = context;
            listall2 = listall;
            generateDataset('A', 'Z', false);
        }

        public void generateDataset(char from, char to, boolean clear) {

            if (clear) clear();
//            final int sectionsNumber = to - from + 1;
//            prepareSections(sectionsNumber);
//            int sectionPosition = 0, listPosition = 0;
//            for (char i=0; i<sectionsNumber; i++) {
//                Item section = new Item(Item.SECTION, String.valueOf((char)('A' + i)));
//                section.sectionPosition = sectionPosition;
//                section.listPosition = listPosition++;
//                onSectionAdded(section, sectionPosition);
//                add(section);
//                final int itemsNumber = (int) Math.abs((Math.cos(2f*Math.PI/3f * sectionsNumber / (i+1f)) * 25f));
//                for (int j=0;j<itemsNumber;j++) {
//                    Item item = new Item(Item.ITEM, section.text.toUpperCase(Locale.ENGLISH) + " - " + j);
//                    item.sectionPosition = sectionPosition;
//                    item.listPosition = listPosition++;
//                    add(item);
//                }
//                sectionPosition++;
//            }
            final int sectionsNumber = 1;
            prepareSections(sectionsNumber);
            int sectionPosition = 0, listPosition = 0;
            for (char i = 0; i < sectionsNumber; i++) {
                Item section = new Item(Item.SECTION, String.valueOf((char) ('A' + i)));
                section.sectionPosition = sectionPosition;
                section.listPosition = listPosition++;
                onSectionAdded(section, sectionPosition);
//                add(section);//添加头
                final int itemsNumber = (int) Math.abs((Math.cos(2f * Math.PI / 3f * sectionsNumber / (i + 1f)) * 25f));
                for (int j = 0; j < listall2.size(); j++) {
                    Item item = new Item(Item.ITEM, section.text.toUpperCase(Locale.ENGLISH) + " - " + j);
                    item.sectionPosition = sectionPosition;
                    item.listPosition = listPosition++;
                    item.createTime = listall2.get(j).getCreateTime();
                    item.userName = listall2.get(j).getUserName();
                    item.isTransfered = listall2.get(j).isIsTransfered();
                    add(item);
                }
                sectionPosition++;
            }

        }

        public void setlist(List<TransferForDoingResult.DataBean> listall) {
            clear();
            listall2 = listall;
            final int sectionsNumber = 1;
            prepareSections(sectionsNumber);
            int sectionPosition = 0, listPosition = 0;
            for (char i = 0; i < sectionsNumber; i++) {
                Item section = new Item(Item.SECTION, String.valueOf((char) ('A' + i)));
                section.sectionPosition = sectionPosition;
                section.listPosition = listPosition++;
                onSectionAdded(section, sectionPosition);
//                add(section);
                final int itemsNumber = (int) Math.abs((Math.cos(2f * Math.PI / 3f * sectionsNumber / (i + 1f)) * 25f));
                for (int j = 0; j < listall2.size(); j++) {
                    Item item = new Item(Item.ITEM, section.text.toUpperCase(Locale.ENGLISH) + " - " + j);
                    item.sectionPosition = sectionPosition;
                    item.listPosition = listPosition++;
                    item.createTime = listall2.get(j).getCreateTime();
                    item.userName = listall2.get(j).getUserName();
                    item.isTransfered = listall2.get(j).isIsTransfered();
                    add(item);
                }
                sectionPosition++;
            }
            notifyDataSetChanged();
        }

        ;

        protected void prepareSections(int sectionsNumber) {
        }

        protected void onSectionAdded(Item section, int sectionPosition) {
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
//            convertView = LayoutInflater.from(context1).inflate(R.layout.item_buydanchelist, null);
//            TextView view = convertView.findViewById(R.id.tv_itemtype);
//            view.setTextColor(Color.DKGRAY);
//            view.setTag("" + position);
            Item item = getItem(position);
            if (item.type == Item.SECTION) {
                //view.setOnClickListener(PinnedSectionListActivity.this);
                convertView = LayoutInflater.from(context1).inflate(R.layout.item_buydantop, null);
                return convertView;
            }
//            view.setText(item.userName + position);
            convertView = LayoutInflater.from(context1).inflate(R.layout.adapter_item, null);
            TextView textView = (TextView) convertView.findViewById(R.id.yihuodongzhuanrangitem_buyinfo);
//        textView.setText(list.get(position));
            textView.setVisibility(View.GONE);
            TextView bikephone = (TextView) convertView.findViewById(R.id.bikephone);
            bikephone.setText(TextUtils.toFormatPhone(item.userName));
            TextView biketime = (TextView) convertView.findViewById(R.id.biketime);
            biketime.setText(item.createTime);
            TextView yihuodongzhuanrangitem_isbuy = (TextView) convertView.findViewById(R.id.yihuodongzhuanrangitem_isbuy);
            ImageView dancheyanse = convertView.findViewById(R.id.dancheyanse);
            ImageView yihuodongzhuanrangitem_isbuyicon = convertView.findViewById(R.id.yihuodongzhuanrangitem_isbuyicon);
            if (item.isTransfered) {
                textView.setBackground(context1.getResources().getDrawable(R.drawable.danchejiaoyibuy));
                yihuodongzhuanrangitem_isbuy.setText("转让中");
                yihuodongzhuanrangitem_isbuy.setTextColor(context1.getResources().getColor(R.color.colorAccent));
                dancheyanse.setImageDrawable(context1.getResources().getDrawable(R.drawable.danchehong));
                yihuodongzhuanrangitem_isbuyicon.setImageDrawable(context1.getResources().getDrawable(R.drawable.zhuanrang1));
            } else {

//                textView.setBackground(context1.getResources().getDrawable(R.drawable.danchejiaoyisell));
//                yihuodongzhuanrangitem_isbuy.setText("求购中");
//                yihuodongzhuanrangitem_isbuy.setTextColor(context1.getResources().getColor(R.color.result_points));
//                dancheyanse.setImageDrawable(context1.getResources().getDrawable(R.drawable.danchelv));
//                yihuodongzhuanrangitem_isbuyicon.setImageDrawable(context1.getResources().getDrawable(R.drawable.goumai));
                textView.setBackground(context1.getResources().getDrawable(R.drawable.danchejiaoyibuy));
                yihuodongzhuanrangitem_isbuy.setText("转让中");
                yihuodongzhuanrangitem_isbuy.setTextColor(context1.getResources().getColor(R.color.colorAccent));
                dancheyanse.setImageDrawable(context1.getResources().getDrawable(R.drawable.danchehong));
                yihuodongzhuanrangitem_isbuyicon.setImageDrawable(context1.getResources().getDrawable(R.drawable.zhuanrang1));
            }
            return convertView;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            return getItem(position).type;
        }

        @Override
        public boolean isItemViewTypePinned(int viewType) {
            return viewType == Item.SECTION;
        }

    }

    static class Item {

        public static final int ITEM = 0;
        public static final int SECTION = 1;

        public final int type;
        public final String text;

        public int sectionPosition;
        public int listPosition;
        public String userName;
        public String createTime;
        public boolean isTransfered;

        public Item(int type, String text) {
            this.type = type;
            this.text = text;
        }

        @Override
        public String toString() {
            return text;
        }

    }

    class MyListener2 extends MyListener {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
            super.onRefresh(pullToRefreshLayout);
            refreshtype = 1;
            page = 1;
            ismore = true;
            getMsggg();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
            super.onLoadMore(pullToRefreshLayout);
            refreshtype = 2;
            if (ismore) {
                page++;
                getMsggg();
            } else {
                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 1) {

        } else if (requestCode == 10010 && resultCode == 1) {//转让
            ((MybikeActivity6) getActivity()).f2.datafalsh();
            ((MybikeActivity6) getActivity()).f1.getMsg();
        } else if (requestCode == 400 && resultCode == 1) {

        } else if (requestCode == 500 && resultCode == 1) {

        }
    }

    public void datafalsh() {
        alllist.clear();
        refreshtype = 0;
        page = 1;//页码
        ismore = true;//判断是否还有更多数据
        getMsggg();
    }
}
